package com.empress.uranus.zma.biz.machine.impl;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.empress.uranus.zma.biz.machine.MCServerInboundHandlerBiz;
import com.empress.uranus.zma.domain.machine.packet.WarehousePacket;
import com.empress.uranus.zma.service.model.WarehousePacketModel;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;

@ChannelHandler.Sharable
@Service("mcserverInboundHandlerBiz")
public class MCServerInboundHandlerBizImpl extends MCServerInboundHandlerBiz {

	private final static Logger LOGGER = LoggerFactory.getLogger(MCServerInboundHandlerBizImpl.class);

    @Override
	public void channelRead(ChannelHandlerContext ctx, Object receivedMessage) {
    	
    	LOGGER.info("the napkin machine server receiving handler channel read: ctx :" + ctx);
		
    	ByteBuf clientBytesBuffer = (ByteBuf)receivedMessage;
    	//从纸巾机客户端读出bytes后，先进行检查过滤，再转换成业务端的报文
    	int clientBytesBufferLength = clientBytesBuffer.readableBytes();
    	if(clientBytesBufferLength < 8){
			 
    		LOGGER.error("receiving error packet bytes from napkin machine, the received length is {}", clientBytesBufferLength);
    		return;
    	}
    	byte[] clientBytes = new byte[clientBytesBufferLength];
    	clientBytesBuffer.readBytes(clientBytes);
		 
    	WarehousePacket warehousePacket = WarehousePacketModel.buildWarehousePacketModel(clientBytes);
    	if(warehousePacket == null) return;
		 
    	// 通知执行下一个InboundHandler
    	ctx.fireChannelRead(warehousePacket);
	}
	
	@Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		ctx.close();
    }
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
		LOGGER.error("handling message in napkin server caused exception", cause);
		ctx.close();
	}
}
